/**
 * Created by Administrator on 2017/1/16.
 */

var MJPlayer = require('../MJ/player').MJPlayer;
var MJ = require('../MJ/MJ');
var Const = require('./const');
var SubCode = require('../subCode');

exports.GXDDZPlayer = MJPlayer.extend({
    _gangTasks: [],

    init: function (uid, msg) {
        this._super(uid, msg);

        this._stat.zmCount = 0;             // 自摸次数
        this._stat.dpCount = 0;             // 点炮次数
        this._stat.dhCount = 0;             // 点胡次数
        this._stat.anGangCount = 0;        // 暗杠次数
        this._stat.mingGangCount = 0;      // 明杠次数
        this._stat.lzCount = 0;             // 庄家次数
        this._stat.roundRules = {};         // 本轮加法玩法

        this._gangTasks = [];
    },

    getPengCount: function () {
        return this._pengCards.length;
    },

    //计算杠分
    settlementGangScore: function () {
        var player = this;
        var room = player.getRoom();        //房间信息
        var gameRule = room.getOption("RULE");      // 房间规则信息
        var dealer = room.getPlayerByIndex(room.getDealerIndex());  //庄的位置

        for (var i = 0, l = player._gangCards.length; i < l; ++i) {
            var gangInfo = player._gangCards[i];
            if (gangInfo.unscored) {
                continue;
            }

            var score = Const.GangScore[gangInfo.gang];
            if (room.getDealerIndex() == player.getIndex() && (gameRule == 1 || gameRule == 3)) {//带庄的玩法 就翻倍
                score *= 2;
            }
            if (gangInfo.gang == MJ.Gang.AN || gangInfo.gang == MJ.Gang.ANS) {
                room.enumPlayers(function (eIndex, ePlayer) {
                    if (eIndex != player.getIndex()) {
                        var tempScore = score;
                        if (eIndex == room.getDealerIndex() && (gameRule == 1 || gameRule == 3)) {
                            tempScore *= 2;
                        }
                        player.addRoundGangScore(tempScore);
                        ePlayer.addRoundGangScore(-tempScore);
                        if (room._baoIndex == player.getIndex()) {//如果当前计分玩家是宝，则分数也加给庄家
                            ePlayer.addRoundGangScore(-tempScore);
                            dealer.addRoundGangScore(+tempScore);
                        } else if (room._baoIndex == eIndex) {//如果当前扣分玩家是宝，则分数也要减给庄家
                            dealer.addRoundGangScore(-tempScore);
                            player.addRoundGangScore(tempScore);
                        }
                    }
                });
            } else if (gangInfo.gang == MJ.Gang.DIAN) {
                var dgPlayer = room.getPlayerByIndex(gangInfo.from);
                var tempScore = score;
                if (gameRule == 1 || gameRule == 3) {
                    if (player.getIndex() != room.getDealerIndex()) {
                        if (gangInfo.from == room.getDealerIndex()) {
                            tempScore *= 2;
                        }
                    }
                }
                dgPlayer.addRoundGangScore(-tempScore);
                player.addRoundGangScore(tempScore);
                if (dgPlayer.getIndex() == room._baoIndex) {
                    dealer.addRoundGangScore(-tempScore);
                    player.addRoundGangScore(tempScore);
                } else if (player.getIndex() == room._baoIndex) {
                    dgPlayer.addRoundGangScore(-tempScore);
                    dealer.addRoundGangScore(tempScore);
                }
            } else if (gangInfo.gang == MJ.Gang.BA) {
                var fromIndex = this._pengCardsFrom[gangInfo.card];
                var fromPlayer = room.getPlayerByIndex(fromIndex);
                if (fromPlayer) {
                    var tempScore = score;
                    if (fromIndex == room.getDealerIndex() && (gameRule == 1 || gameRule == 3)) {
                        tempScore *= 2;
                    }
                    player.addRoundGangScore(tempScore);
                    fromPlayer.addRoundGangScore(-tempScore);
                    if (room._baoIndex == player.getIndex()) {//如果当前计分玩家是宝，则分数也加给庄家
                        fromPlayer.addRoundGangScore(-tempScore);
                        dealer.addRoundGangScore(+tempScore);
                    } else if (fromIndex == room._baoIndex) {//如果当前扣分玩家是宝，则分数也要减给庄家
                        dealer.addRoundGangScore(-tempScore);
                        player.addRoundGangScore(tempScore);
                    }
                }
            }
        }
    },

    settlementPatternScore: function () {
        var player = this;
        var room = this.getRoom();
        var dpPlayer = room.getPlayerByIndex(room.getFirstDPIndex());
        var dealer = room.getPlayerByIndex(room.getDealerIndex());

        // 计算每个人的加分项
        room.enumPlayers(function (eIndex, ePlayer) {
            ExObject.each(ePlayer._stat.roundRules, function (rule, value) {
                ePlayer.addRoundItemScores(rule, Const.ItemScore[rule]);
                ePlayer.setRoundScoreRule(rule);
            });
        });

        if (!this.isRoundHu()) {
            return;
        }
        var hasTHorDIHU = false;
        // var isQG = false;
        var itemScoreCount = 0;
        ExObject.each(this._stat.roundScoreRules, function (rule, value) {
            if (rule == Const.ScoreRule.GSH) {
                hasGSH = true;
            }
            if (rule == Const.ScoreRule.TH || rule == Const.ScoreRule.DIHU) {
                hasTHorDIHU = true;
                player.setRoundPattern(0, 0);
            }
            itemScoreCount++;
        }.bind(this));

        // 结算牌型及基础分
        var basicScore = this._stat.roundPatternScore + ExObject.sumValue(this._stat.roundItemScores);

        var gameRule = room.getOption("RULE");
        if (dealer.getIndex() == player.getIndex() && (gameRule == 1 || gameRule == 3)) {//带庄的玩法 翻1倍
            basicScore *= 2;
        }
        var maxScore = room.getOption("MAXSCORE");//获取封顶分数
        basicScore = basicScore >= maxScore ? maxScore : basicScore;


        this._stat.roundTarget.forEach(function (playerIndex) {
            var target = room.getPlayerByIndex(playerIndex);
            var targetScore = basicScore;
            if (playerIndex == room.getDealerIndex() && (gameRule == 1 || gameRule == 3)) {
                targetScore *= 2;
            }
            targetScore = targetScore > maxScore ? maxScore : targetScore;
            if (targetScore > maxScore) {
                targetScore = maxScore
            } else {
                var roundScore = target._stat.roundScore;
                var tmp = roundScore > 0 ? (maxScore + roundScore) : (maxScore - roundScore);
                targetScore = targetScore > tmp ? tmp : targetScore;
            }
            if (target) {
                if (player.getIndex() == room._baoIndex) {//如果当前计分玩家是宝，则当前扣分玩家还要扣一份给庄家
                    if (targetScore > maxScore / 2 && target.getIndex() != dealer.getIndex()) {
                        targetScore = maxScore / 2;
                    }
                    dealer.addRoundScore(targetScore);
                    target.addRoundScore(-targetScore);
                } else if (target.getIndex() == room._baoIndex) {//如果当前扣分玩家是宝，则庄家还要扣一份给当前计分玩家
                    if (targetScore > maxScore / 2) {
                        if (target.getIndex() == dealer.getIndex()) {
                            targetScore = maxScore / 2;
                        }
                    }
                    dealer.addRoundScore(-targetScore);
                    player.addRoundScore(targetScore);
                }

                target.addRoundScore(-targetScore);
                target.addRoundScoreDetail(player.getRoundResult(), -targetScore);
                player.addRoundScore(targetScore);
            }
        });
    },

    settlementRules: function () {
        //以下规则只针对赢家有效
        if (!this.isRoundHu()) {
            return;
        }
        var player = this;
        var room = player.getRoom();
        var rules = player._stat.roundScoreRules;
        var cards = player.getRoundHuCards();
        var hasGSH = false;
        var hasTHorDIHU = false;
        var hasQG = false;

        ExObject.each(rules, function (rule, value) {
            if (rule == Const.ScoreRule.GSH) {
                hasGSH = true;
            }
            if (rule == Const.ScoreRule.TH || rule == Const.ScoreRule.DIHU) {
                hasTHorDIHU = true;
            }
            if (rule == Const.ScoreRule.QG) {
                hasQG = true;
            }
        });

        if (hasTHorDIHU || hasGSH || hasQG) {
            return;
        }

        // 判断 清一色/豪华清一色/全求人清一色
        var colors = player.getColorsWithCards(cards);
        var pattern = player.checkHu();
        if (player.getRoundResult() == MJ.Result.DH) {
            var pattern = player.checkHuWithCard(this.getRoundHuCard());
        }
        if (pattern == Const.Pattern.ZYS) {
            return;
        }

        if (colors.length == 1) {
            var rule = Const.ScoreRule.QingYiSe;
            if (pattern == Const.Pattern.SINGLE) {
                rule = Const.ScoreRule.QQRQYS;
            } else if (pattern == Const.Pattern.HHQD) {
                rule = Const.ScoreRule.HHQDQYS;
            }
            var ruleScore = Const.ItemScore[rule];
            player.setRoundScoreRule(rule);
            player.addRoundItemScores(rule, ruleScore);
        }
    },

    settlement: function () {
        this._super();

        this.addRoundScore(this._stat.roundGangScore);
        this.addRoundScore(this._stat.roundPiaoScore);

        if (this._stat.roundResult == MJ.Result.ZM) {
            this._stat.zmCount++;
        } else if (this._stat.roundResult == MJ.Result.DH) {
            this._stat.dhCount++;
            if (this._stat.roundTarget.length > 0) {
                var dpPlayer = this.getRoom().getPlayerByIndex(this._stat.roundTarget[0]);
                if (dpPlayer) {
                    dpPlayer._stat.dpCount++;
                }
            }
        }

        for (var i = 0, l = this._gangCards.length; i < l; ++i) {
            var gangInfo = this._gangCards[i];
            if (gangInfo.type) {

            } else {
                if (gangInfo.gang == MJ.Gang.AN || gangInfo.gang == MJ.Gang.ANS) {
                    this._stat.anGangCount++;
                } else {
                    this._stat.mingGangCount++;
                }
            }
        }

        if (this.isDealer()) {
            this._stat.lzCount++;
        }
    },

    /******************************************************************
     * 重载的接口
     ******************************************************************/

    getReconnectInfo: function (isSelf) {
        var info = this._super(isSelf);
        // info.selectPiao = this._selectPiao;
        return info;
    },

    cancelLastGangForQG: function (card) {
        var gangIndex = this._gangCards.length - 1;
        if (gangIndex < 0) {
            return;
        }

        var gangInfo = this._gangCards[gangIndex];
        if (gangInfo.card != card) {
            return;
        }

        this.getRoom().broadcast("onCancelGangForQG", {
            playerIndex: this.getIndex(),
            gangInfo: gangInfo,
        });

        if (gangInfo.gang == MJ.Gang.BA) {
            this._pengCards.push(card);
            this._playCards.push({card: card, task: MJ.Task.HU});
        } else if (gangInfo.gang == MJ.Gang.DIAN) {
            this._handCards.addCard(card, 3);
        } else {
            this._handCards.addCard(card, 3);
            this._playCards.push({card: card, task: MJ.Task.HU});
        }

        this._gangCards.splice(gangIndex, 1);
        return gangInfo;
    },

    getSettlementInfo: function () {
        var info = this._super();
        info.gangCards = this._gangCards;
        info.pengCards = this._pengCards;
        info.chiCards = this._chiCards;
        info.handCards = this._handCards.getCards();
        info.pengCardsFrom = this._pengCardsFrom;
        return info;
    },

    // gangCard: function (gangTask) {
    //     var selectGang = gangTask.selectGang || 0;
    //     if (selectGang > gangTask.gangArray.length) {
    //         selectGang = 0;
    //     }
    //
    //     var selectGangTask = gangTask.gangArray[selectGang];
    //
    //     return selectGangTask;
    // },

    onStartNewRound: function () {
        this._super();
        this._selectPiao = -1;
        this._stat.roundRules = {};
        this._stat.roundPiaoScore = 0;
        this._gangTasks = [];
    },

    checkHuLogic: function (cards, huCard) {
        var num4 = 0;
        var num3 = 0;
        var num2 = 0;
        var numAll = 0;
        var ziNum = 0;

        ExObject.each(cards, function (c, n) {
            if (n == 2) {
                num2++;
            } else if (n == 3) {
                num3++;
            } else if (n == 4) {
                num4++;
            }
            if (c > 0 && c <= 7) {
                ziNum += n;
            }
            numAll += n;
        });

        if (numAll == 2 && num2 == 1) { // 全球人
            return MJ.Pattern.SINGLE;
        }

        if (num2 == 7 || (num2 + num4 * 2) == 7) {// 七对
            if (num4 >= 1) { // 豪华七对
                return Const.Pattern.HHQD;
            }
            return Const.Pattern.PAIR7;
        }

        if ((num2 == 1) && ((num3 * 3 + 2) == numAll)) { // 碰碰胡
            return Const.Pattern.PAIR;
        }

        if (ziNum == numAll) {
            var pengCards = this._pengCards;
            var gangCards = this._gangCards;
            var isZiPeng = true;
            var isZiGang = true;
            for (var i = 0; i < pengCards.length; i++) {
                if (pengCards[i] > 7) {
                    isZiPeng = false;
                }
            }
            for (var i = 0; i < gangCards.length; i++) {
                if (gangCards[i].card > 7) {
                    isZiGang = false;
                }
            }
            if (isZiPeng && isZiGang) {
                return Const.Pattern.ZYS;
            }
        }

        var room = this.getRoom();
        var colors = room.getSubConfig().colors;

        var color3X2Num = 0; //牌数为3X2的花色数量
        var pattern = MJ.Pattern.NORMAL;
        for (var i = 0, l = colors.length; i < l; ++i) {
            var color = colors[i];
            var colorCards = MJ.getColorCards(cards, color);
            var colorCardNum = ExObject.sumValue(colorCards);
            if (colorCardNum == 0) {
                continue;
            }

            if (colorCardNum%3 == 1) {
                pattern = MJ.Pattern.NONE;
                break;
            }

            if (colorCardNum%3 == 2) {
                color3X2Num++;
                if (color3X2Num > 1) {
                    pattern = MJ.Pattern.NONE;
                    break;
                }
            }

            if (MJ.isBasicColor(color)) {
                if (!MJ.checkHuColorCards(MJ.getValue(color, 1), MJ.getValue(color, MJ.COLOR_CARD_NUM), colorCards)) {
                    pattern = MJ.Pattern.NONE;
                    break;
                }
            } else {
                if (!MJ.checkPairHuColorCards(colorCards)) {
                    pattern = MJ.Pattern.NONE;
                    break;
                }
            }
        }

        if (this.getTingCards().length == 1 && pattern == MJ.Pattern.NORMAL) {// 卡单胡
            return Const.Pattern.KADAN;
        }

        // pattern = this._super(cards, huCard);

        // if (pattern == MJ.Pattern.NORMAL && (num2 == 3 || num2 == 4)) {
        //     pattern = Const.Pattern.NONE;
        // }

        return pattern;
    },

    gangCard: function (gangTask) {
        var selectGang = gangTask.selectGang || 0;
        if (selectGang > gangTask.gangArray.length) {
            selectGang = 0;
        }

        var selectGangTask = gangTask.gangArray[selectGang];

        if (selectGangTask.type) {
            return this._specGangCard(selectGangTask);
        } else {
            return this._super(selectGangTask);
        }
    },

    _getSpecGang: function (type) {
        var result = null;
        for (var i = 0, l = this._gangCards.length; i < l; ++i) {
            var gangInfo = this._gangCards[i];
            if (gangInfo.type == type) {
                result = gangInfo;
                break;
            }
        }
        return result;
    },

    _specGangCard: function (gangTask) {
        var gangInfo = null;
        var self = this;

        if (gangTask.buCard) {
            gangInfo = this._getSpecGang(gangTask.type);
            if (gangInfo) {
                if (!gangInfo.buCards) {
                    gangInfo.buCards = [];
                }

                var buCard = gangTask.buCard;
                if (this._handCards.getCardNum(buCard) > 0) {
                    this._handCards.delCard(buCard);
                    gangInfo.buCards.push(buCard);
                }

                gangInfo.buCard = gangTask.buCard;
            }
        } else if (gangTask.cards) {
            gangTask.cards.forEach(function (card) {
                this._handCards.delCard(card);
            }.bind(this));

            gangInfo = clone(gangTask);
            delete gangInfo.playerIndex;
            this._gangCards.push(gangInfo);
        }

        return gangInfo;
    },

    /**
     * 检查杠
     * @returns []
     */
    checkGang: function () {
        var room = this.getRoom();
        var gangArray = [];

        var lastCard = this._handCards.getLastNewCard();
        if (this.getIndex() != room.getCurPlay() || room.getCurTask()) {
            lastCard = 0;
        }

        if (lastCard) { //优先杠刚摸上的牌
            if (this._handCards.getCardNum(lastCard) == 4) {
                gangArray.push({card: lastCard, gang: MJ.Gang.AN});
            }

            if (this._pengCards.indexOf(lastCard) != -1) {
                gangArray.push({card: lastCard, gang: MJ.Gang.BA});
            }
        }

        var anGangCards = this._handCards.getAnGangCards();
        for (var i = 0; i < anGangCards.length; ++i) {
            if (anGangCards[i] != lastCard) {
                var gangInfo = {card: anGangCards[i], gang: MJ.Gang.ANS};
                if (this.getRoom().getHideOption("anGangOverdue")) {
                    if (this.getPlayHand() != this.getRoom().getCurGang()) {
                        //gangInfo.overdue = true;
                    }
                }
                gangArray.push(gangInfo);
            }
        }

        this._pengCards.forEach(function (card) {
            if (this._handCards.getCardNum(card) > 0) {
                if (card != lastCard) {
                    gangArray.push({card: card, gang: MJ.Gang.BA, overdue: true});
                }
            }
        }.bind(this));

        var from = this.getIndex();
        gangArray.forEach(function (gangInfo) {
            gangInfo.from = from;
        });

        return gangArray;
    },
    // 预设牌型
    getInitHandCardPreCards: function () {
        var preCards = [];

        var distance = this.getRoom().getIndexDistance(this.getIndex(), this.getRoom().getDealerIndex());
        if (distance == 0) {
            // preCards.push(MJ.getValue(MJ.Color.TONG, 4));
            // preCards.push(MJ.getValue(MJ.Color.TONG, 4));
            // preCards.push(MJ.getValue(MJ.Color.TONG, 4));
            // preCards.push(MJ.getValue(MJ.Color.TONG, 5));
            // preCards.push(MJ.getValue(MJ.Color.TONG, 5));
            // preCards.push(MJ.getValue(MJ.Color.TONG, 5));
            // preCards.push(MJ.getValue(MJ.Color.ZI, 3));
            // preCards.push(MJ.getValue(MJ.Color.ZI, 3));
            // preCards.push(MJ.getValue(MJ.Color.TIAO, 5));
            // preCards.push(MJ.getValue(MJ.Color.WAN, 2));
            // preCards.push(MJ.getValue(MJ.Color.WAN, 3));
            // preCards.push(MJ.getValue(MJ.Color.WAN, 7));
            // preCards.push(MJ.getValue(MJ.Color.WAN, 7));

            // preCards.push(MJ.getValue(MJ.Color.TONG, 3));
            // preCards.push(MJ.getValue(MJ.Color.TONG, 3));
            // preCards.push(MJ.getValue(MJ.Color.TONG, 1));
            // preCards.push(MJ.getValue(MJ.Color.TONG, 4));
            // preCards.push(MJ.getValue(MJ.Color.TONG, 4));
            // preCards.push(MJ.getValue(MJ.Color.TONG, 2));
            // preCards.push(MJ.getValue(MJ.Color.TONG, 2));
            // preCards.push(MJ.getValue(MJ.Color.TONG, 2));
            // preCards.push(MJ.getValue(MJ.Color.TONG, 4));
            // preCards.push(MJ.getValue(MJ.Color.TONG, 9));
            // preCards.push(MJ.getValue(MJ.Color.TONG, 6));
            // preCards.push(MJ.getValue(MJ.Color.TONG, 6));
            // preCards.push(MJ.getValue(MJ.Color.TONG, 7));
            // preCards.push(MJ.getValue(MJ.Color.TONG, 1));


            // kd duizi
            // preCards.push(MJ.getValue(MJ.Color.WAN, 1));
            // preCards.push(MJ.getValue(MJ.Color.WAN, 1));
            // preCards.push(MJ.getValue(MJ.Color.WAN, 3));
            // preCards.push(MJ.getValue(MJ.Color.WAN, 3));
            // preCards.push(MJ.getValue(MJ.Color.TIAO, 5));
            // preCards.push(MJ.getValue(MJ.Color.TIAO, 5));
            // preCards.push(MJ.getValue(MJ.Color.TIAO, 7));
            // preCards.push(MJ.getValue(MJ.Color.TIAO, 7));
            // preCards.push(MJ.getValue(MJ.Color.WAN, 7));
            // preCards.push(MJ.getValue(MJ.Color.WAN, 8));
            // preCards.push(MJ.getValue(MJ.Color.WAN, 9));
            // preCards.push(MJ.getValue(MJ.Color.TONG, 8));
            // preCards.push(MJ.getValue(MJ.Color.TONG, 1));
            // preCards.push(MJ.getValue(MJ.Color.ZI, 5));
            //kd lianzi
            // preCards.push(MJ.getValue(MJ.Color.WAN, 1));
            // preCards.push(MJ.getValue(MJ.Color.WAN, 1));
            // preCards.push(MJ.getValue(MJ.Color.WAN, 3));
            // preCards.push(MJ.getValue(MJ.Color.WAN, 3));
            // preCards.push(MJ.getValue(MJ.Color.WAN, 5));
            // preCards.push(MJ.getValue(MJ.Color.WAN, 5));
            // preCards.push(MJ.getValue(MJ.Color.WAN, 6));
            // preCards.push(MJ.getValue(MJ.Color.WAN, 6));
            // preCards.push(MJ.getValue(MJ.Color.WAN, 6));
            // preCards.push(MJ.getValue(MJ.Color.TIAO, 4));
            // preCards.push(MJ.getValue(MJ.Color.TIAO, 6));
            // preCards.push(MJ.getValue(MJ.Color.WAN, 8));
            // preCards.push(MJ.getValue(MJ.Color.WAN, 9));
            // preCards.push(MJ.getValue(MJ.Color.WAN, 7));
        } else if (distance == 1) {
            // preCards.push(MJ.getValue(MJ.Color.WAN, 3));
            // preCards.push(MJ.getValue(MJ.Color.WAN, 3));
            // preCards.push(MJ.getValue(MJ.Color.WAN, 3));
            // preCards.push(MJ.getValue(MJ.Color.WAN, 6));
            // preCards.push(MJ.getValue(MJ.Color.WAN, 6));
            // preCards.push(MJ.getValue(MJ.Color.WAN, 6));
            // preCards.push(MJ.getValue(MJ.Color.TIAO, 2));
            // preCards.push(MJ.getValue(MJ.Color.ZI, 3));
            // preCards.push(MJ.getValue(MJ.Color.TIAO, 2));
            // preCards.push(MJ.getValue(MJ.Color.TIAO, 2));
            // preCards.push(MJ.getValue(MJ.Color.ZI, 3));
            // preCards.push(MJ.getValue(MJ.Color.ZI, 3));
            // preCards.push(MJ.getValue(MJ.Color.TONG, 8));

            // preCards.push(MJ.getValue(MJ.Color.ZI, 1));
            // preCards.push(MJ.getValue(MJ.Color.ZI, 2));
            // preCards.push(MJ.getValue(MJ.Color.ZI, 3));
            // preCards.push(MJ.getValue(MJ.Color.ZI, 4));
            // preCards.push(MJ.getValue(MJ.Color.ZI, 5));
            // preCards.push(MJ.getValue(MJ.Color.ZI, 6));
            // preCards.push(MJ.getValue(MJ.Color.ZI, 7));
            // preCards.push(MJ.getValue(MJ.Color.ZI, 1));
            // preCards.push(MJ.getValue(MJ.Color.ZI, 2));
            // preCards.push(MJ.getValue(MJ.Color.ZI, 3));
            // preCards.push(MJ.getValue(MJ.Color.ZI, 4));
            // preCards.push(MJ.getValue(MJ.Color.ZI, 5));
            // preCards.push(MJ.getValue(MJ.Color.ZI, 6));
        }
        return preCards;
    },
});